package it.polimi.TravelDream;

import javax.annotation.Resource;
import javax.ejb.EJBContext;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 * Session Bean implementation class UserBean
 */
@Stateless
public class UserMgrBean implements UserMgr {

	@PersistenceContext
    private EntityManager em;
	
	@Resource
	private EJBContext context; 
	
	@Override
	public boolean checkEMail(String email){
		try {
			User u = em.createNamedQuery(User.GetCurrent, User.class)
			.setParameter("param", email)
			.getSingleResult();
			return true;
		} catch (Exception e) {
			return false;
		}

	}

	@Override
	public void save(UserDTO user) {
		User newUser = new User(user);
		newUser.setGroups(Groups_Names.USER);
		em.persist(newUser);
		em.flush();
	}

	@Override
	public void update(UserDTO user) {
		User modUser = new User();
		modUser = em.merge(em.find(User.class, user.getID()));
		modUser.setName(user.getName());
		modUser.setSurname(user.getSurname());
		
	}	
    
    public User getCurrentUser(){
    	return em.createNamedQuery(User.GetCurrent, User.class)
    			.setParameter("param", context.getCallerPrincipal().getName())
                .getSingleResult();
    	
    }
    
    public UserDTO getCurrentUserDTO(){
    	return convertToDTO(getCurrentUser());
    }

    protected static UserDTO convertToDTO(User user) {
		UserDTO userDTO = new UserDTO();
		userDTO.setEmail(user.getEmail());
		userDTO.setName(user.getName());
		userDTO.setSurname(user.getSurname());;
		userDTO.setTelephone(user.getTelephone());
		userDTO.setBirthday(user.getBirthDate());
		userDTO.setID(user.getId());
		return userDTO;
	}
    
    
}
